package edu.yuhf.pac;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class StorageForReentrantLock extends Storage{
		int MAX_NUM=100;
	private Lock lock=new ReentrantLock();
		Condition full=lock.newCondition();
		Condition empty=lock.newCondition();
			
			public void produce(int number) {
				lock.lock();  		//请求lock锁
				try {
				
				 						
				while(list.size()+number>=MAX_NUM) {
					System.out.println("仓库已满，无法生产"+number+"产品");
				
					try {
					
						full.await(); 					//await 挂起线程 并释放锁 其他线程可以 重新调用并请求锁
					 }catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				for(int i=0;i<number;i++) {
					list.add(new Product(i,Thread.currentThread().getName()+"_"+i));
					
				}
				System.out.println("已经生产了"+number+"件商品，仓库中共有"+list.size()+"件产品");
				empty.signalAll();					//唤醒一个在 await()等待队列中的线程(消费线程如果挂起则会被唤醒)。与Object.notify()相似		
				
			}
			finally {
				lock.unlock();                          //释放lock锁 需要手动释放
			}
			}
			public void buy(int number) {
				lock.lock();
				try {
					while(list.size()-number<0) {
						System.out.println("仓库不足 无法消费"+number+"件产品");
						try {
							empty.await();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}		
					}
						for(int i=0;i<number;i++) {
							list.remove();
						}
						System.out.println("已经消费了"+number+"件商品，仓库中还剩"+(list.size())+"件产品");
						full.signalAll();                        //唤醒一个在 await()等待队列中的线程(生产线程如果被挂起则会被唤醒)。与Object.notify()相似
					
				}finally {
					lock.unlock();
				}
			}
			
			
			
			
			
			
}
